import { Inject, Injectable } from '@nestjs/common';
import { CreateShipinleibieDto } from './dto/create-shipinleibie.dto';
import { UpdateShipinleibieDto } from './dto/update-shipinleibie.dto';
import { Like, Repository } from 'typeorm';
import { Shipinleibie } from './entities/shipinleibie.entity';
import { SearchPagesDto } from './dto/search-pages.dto';

@Injectable()
export class ShipinleibieService {
  constructor(
    @Inject('SHIPINLEIBIE_REPOSITORY')
    private shipinleibieRepository: Repository<Shipinleibie>,
  ) {}

  async create(createDto: CreateShipinleibieDto) {
    try {
      const entity = this.shipinleibieRepository.create(createDto);
      return await this.shipinleibieRepository.save(entity);
    } catch (error) {
      throw new Error(`创建失败: ${error.message}`);
    }
  }
  findAll() {
    return this.shipinleibieRepository.find();
  }
  async findAllPage(pages: SearchPagesDto) {
    const { page = 1, limit = 10, leibie } = pages;
    const skip = (page - 1) * limit;

    const where: Record<string, any> = {};

    if (leibie) {
      where.leibie = Like(`%${leibie}%`);
    }

    const [list, total] = await this.shipinleibieRepository.findAndCount({
      where,
      skip,
      take: limit,
      order: { createTime: 'DESC' },
    });

    return {
      list,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  findOne(id: number) {
    return this.shipinleibieRepository.findOne({
      where: { id },
    });
  }

  async update(id: number, updateDto: UpdateShipinleibieDto) {
    await this.shipinleibieRepository.update(id, updateDto);
    return this.findOne(id);
  }

  remove(id: number) {
    return this.shipinleibieRepository.delete(id);
  }

  async batchRemove(ids: number[]) {
    const result = await this.shipinleibieRepository
      .createQueryBuilder()
      .delete()
      .whereInIds(ids)
      .execute();

    return {
      message: `成功删除 ${result.affected} 条记录`,
      affected: result.affected,
    };
  }
}
